using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace EntityAop.Interceptors.Support
{
    public class InstanceSpecificElement
    {
        public PropertyChangedEventHandler PropertyChangedEventHandler { get; set; }

        private static readonly int[] emptyInverseReference = new int[0];

        protected Dictionary<string, HashSet<int>> InverseDependecies { get; set; }

        public InstanceSpecificElement()
        {
            InverseDependecies = new Dictionary<string, HashSet<int>>();
        }

        public void RegisterInstanceToInverseReference(Type type, int hashCode)
        {
            var fullName = type.FullName;

            if (InverseDependecies.ContainsKey(fullName))
            {
                if (InverseDependecies[fullName].Contains(hashCode))
                {
                    return;
                }

                InverseDependecies[fullName].Add(hashCode);
                return;
            }

            InverseDependecies.Add(fullName, new HashSet<int> { hashCode });
        }

        public void UnregisterInstanceFromInverseReference(Type type, int hashCode)
        {
            var fullName = type.FullName;

            if (InverseDependecies.ContainsKey(fullName) && InverseDependecies[fullName].Contains(hashCode))
            {
                InverseDependecies[fullName].Remove(hashCode);
            }
        }

        public IEnumerable<int> GetRegisteredInverseReferences(string typeFullName)
        {
            if (!InverseDependecies.ContainsKey(typeFullName))
            {
                return emptyInverseReference;
            }

            return InverseDependecies[typeFullName];
        }
    }
}